package com.example.myapplication;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

    public class MyActivity extends AppCompatActivity {

        private TextView mTvResult;
        private EditText mEtName;
        private Button bntAdd;
        private Button btnQuery;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main_layout);

            initView();
            initEvent();
        }

        private void initEvent() {
            bntAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 增加记录
                    String name = mEtName.getText().toString();
                    // 获取resolver
                    ContentResolver resolver = getContentResolver();

                    ContentValues values = new ContentValues();
                    values.put("name",name);  // 准备添加的数据信息,类似于map

                    resolver.insert(
                            Uri.parse("content://com.example.myapplication/info"),
                            values);

                }
            });
            btnQuery.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 获取resolver
                    ContentResolver resolver = getContentResolver();
                    Cursor cursor = resolver.query(Uri.parse("content://com.example.myapplication/info"),
                            null, null, null, null);
                    while (cursor.moveToNext()){
                        String name = cursor.getString(1);
                        mTvResult.setText(name);
                    }
                    cursor.close();


                }
            });
        }

        private void initView() {
            mTvResult = findViewById(R.id.tv_result);
            mEtName = findViewById(R.id.et_name);
            bntAdd = findViewById(R.id.btn_add);
            btnQuery = findViewById(R.id.btn_query);
        }
    }

